<template>
  <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
    <div>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">

        <el-form-item>
          <el-upload class="upload-demo" action="#" :limit="1" :auto-upload="false" v-model:file-list="fileList"
            :on-change="fileOnChange" :on-remove="fileRemove">
            <div class="file-btn">
              <div>
                <el-icon class="el-icon--upload">
                  <IEpUploadFilled />
                </el-icon>
              </div>
              <div class="el-upload__text">
                文件上传
              </div>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { fileApi } from "@/plugins/api/upload";
import { docsAddApi } from "@/plugins/api/customer/manage/file";
const props = defineProps({
  dataInfo: {
    type: Object,
    default: {},
  },
});
let ruleForm = ref({
  valid_limit: 1,
});
let rules = {

};
let dialogVisible = ref(false);
function handleClose(done) {
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => { });
}
let title = ref("");
let ruleFormRef = ref(null);
function initFun() {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  fileList.value = [];

  title.value = "新增";

  dialogVisible.value = true;
}
const emit = defineEmits(["refreshFile"]);
function submit() {
  if (fileList.value.length == 0) return ElMessage.warning("请上传文件！");
  let obj = {
    opportunity_id: props.dataInfo.id,
    filename: fileList.value[0].name,
    url: fileList.value[0].url,
  };

  docsAddApi(obj).then((data) => {
    ElMessage.success("新增成功！");
    dialogVisible.value = false;
    emit("refreshFile");
  });


}
function handleRadio(data) {
  if (data === 0) {
    ruleForm.value.valid_date = "";
  }
}
// 上传
let fileList = ref([]);
function fileOnChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  fileApi(formData).then((resp) => {
    if (resp) {

      fileList.value = [];
      fileList.value.push({
        name: resp.file_name,
        url: resp.file_url,
      });
    } else {
      ElMessage.danger("上传失败！请重新上传！");
    }
  });
}
function fileRemove() {
  fileList.value = [];
}
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.upload-demo {
  width: 100%;
  height: 100%;
  border: 1px dotted rgb(189, 186, 186);
  display: flex;
  flex-direction: column;
  justify-content: center;

  >:deep(div) {
    align-self: center !important;
    text-align: center;
  }

  .file-btn {
    width: 100%;
    height: 100%;
  }

  .el-icon--upload {
    font-size: 60px;
  }


}
</style>
